package zscript

import (
    "context"
    "sync"
)

// Config 配置
type Config struct {
}

type Handler struct {
    Name   string
    Args   map[string]interface{}
    Author   string
    Function Function
}
type Function func(ctx context.Context, name string, args map[string]interface{})

// Script 脚本
type Script struct {
    ctx context.Context

    config   Config
    handlers []Handler
}

func NewScript(ctx context.Context, config Config) *Script {
    return &Script{
        ctx:    ctx,
        config: config,
    }
}

// AddHandle 添加路由
func (s *Script) AddHandle(handlers []Handler) {
    for _, handler := range handlers {
        s.handlers = append(s.handlers, handler)
    }
}

// Start 启动
func (s *Script) Start(wg *sync.WaitGroup) {
    for _, handler := range s.handlers {
        handler := handler
        wg.Add(1)

        go func() {
            defer wg.Done()

            handler.Function(s.ctx, handler.Name, handler.Args)
        }()
    }
}

// StopSignal 终止
func StopSignal(ctx context.Context) bool {
    select {
    case <-ctx.Done():
        return true
    default:
        return false
    }
}
